﻿using DotNetty.Transport.Channels;
using System;
using DotNetty.Handlers.Timeout;

namespace Coldairarrow.DotNettySocket
{
    class CommonChannelHandler : SimpleChannelInboundHandler<object>
    {
        public CommonChannelHandler(IChannelEvent channelEvent)
        {
            _channelEvent = channelEvent;
        }
        IChannelEvent _channelEvent { get; }

        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            ctx.Flush();
            _channelEvent.OnChannelReceive(ctx, msg);

        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            _channelEvent.OnChannelActive(context);
        }

        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            context.Flush();
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            _channelEvent.OnChannelInactive(context.Channel);
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
            _channelEvent.OnException(context.Channel, exception);
        }

        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            //Console.WriteLine("已经15秒未收到客户端的消息了！");
            if (evt is IdleStateEvent eventState)
            {
                if (eventState.State == IdleState.ReaderIdle)
                {
                    //Console.WriteLine("关闭这个不活跃通道！");
                    context.CloseAsync();
                }
            }
            else
            {
                base.UserEventTriggered(context, evt);
            }
        }
    }
}